const { pool } = require('../config/db');
const bcrypt = require('bcryptjs');

class User {
  // 根据用户名查找用户
  static async findByUsername(username) {
    try {
      const [rows] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
      return rows.length ? rows[0] : null;
    } catch (error) {
      console.error('查询用户失败：', error);
      throw error;
    }
  }

  // 根据电子邮件查找用户
  static async findByEmail(email) {
    try {
      const [rows] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
      return rows.length ? rows[0] : null;
    } catch (error) {
      console.error('查询用户失败：', error);
      throw error;
    }
  }

  // 根据ID查找用户
  static async findById(id) {
    try {
      const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [id]);
      return rows.length ? rows[0] : null;
    } catch (error) {
      console.error('查询用户失败：', error);
      throw error;
    }
  }

  // 创建新用户
  static async create(userData) {
    try {
      // 加密密码
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(userData.password, salt);

      const [result] = await pool.query(
        'INSERT INTO users (username, password, email, role) VALUES (?, ?, ?, ?)',
        [userData.username, hashedPassword, userData.email || null, userData.role || 'user']
      );

      return result.insertId;
    } catch (error) {
      console.error('创建用户失败：', error);
      throw error;
    }
  }

  // 更新用户信息
  static async update(id, userData) {
    try {
      let updateFields = [];
      let queryParams = [];

      // 构建动态更新字段
      for (const [key, value] of Object.entries(userData)) {
        if (key !== 'id' && value !== undefined) {
          if (key === 'password') {
            // 如果更新密码，需要加密
            const salt = await bcrypt.genSalt(10);
            const hashedPassword = await bcrypt.hash(value, salt);
            updateFields.push(`${key} = ?`);
            queryParams.push(hashedPassword);
          } else {
            updateFields.push(`${key} = ?`);
            queryParams.push(value);
          }
        }
      }

      if (updateFields.length === 0) {
        return false; // 没有字段需要更新
      }

      queryParams.push(id);
      const [result] = await pool.query(
        `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`,
        queryParams
      );

      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新用户失败：', error);
      throw error;
    }
  }

  // 验证用户密码
  static async verifyPassword(plainPassword, hashedPassword) {
    return await bcrypt.compare(plainPassword, hashedPassword);
  }
}

module.exports = User; 